package com.cmy.framework_utils.toast

import android.content.Context
import android.os.Looper
import android.text.TextUtils
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.StringRes
import com.cmy.framework_utils.R
/**
 * Describe：
 * -Toast提示相关
 *
 * @author cmy
 * CreateTime：2019/11/8
 */

fun String.toast(context:Context,duration: Int = Toast.LENGTH_SHORT) {
    ToastUtils.show(context,this, duration)
}


object ToastUtils {
    //    private val mToast: Toast by lazy {
//        Toast(BaseApp.instance).also {
//            it.setGravity(Gravity.CENTER, 0, 0)
//            val inflater = LayoutInflater.from(BaseApp.instance)
//            val view: View = inflater.inflate(R.layout.layout_toast, null)
//            it.view = view
//        }
//    }
//
//    private val tvToast: TextView by lazy {
//        mToast.view.findViewById<TextView>(R.id.tv_toast)
//    }
//    private var tvToast: TextView? = null
    private var mToast: Toast? = null


    @JvmStatic
    fun show(context:Context,message: CharSequence, duration: Int = Toast.LENGTH_SHORT) {

        try {
            showCustomToast(context,message.toString(), duration)
        } catch (e: Exception) {
            Looper.prepare();
            showCustomToast(context,message.toString(), duration)
            Looper.loop()
        }
    }

    @JvmStatic
    fun showShort(context:Context,@StringRes message: Int) {
        show(context,context.getString(message), Toast.LENGTH_SHORT)
    }

    @JvmStatic
    fun showShort(context:Context,message: CharSequence) {
        show(context,message.toString(), Toast.LENGTH_SHORT)
    }

    @JvmStatic
    fun showLong(context:Context,message: CharSequence) {
        show(context,message.toString(), Toast.LENGTH_LONG)
    }

    /**
     * 自定义toast
     *
     * @param context  application
     * @param message  显示内容
     * @param duration 显示时长
     */
    private fun showCustomToast(context:Context,message: CharSequence, duration: Int = Toast.LENGTH_SHORT) {
        if (TextUtils.isEmpty(message)) {
            return
        }
        mToast?.cancel()
        mToast = Toast(context).also {
            it.setGravity(Gravity.CENTER, 0, 0)
            it.duration = duration
            val inflater = LayoutInflater.from(context)
            val view: View = inflater.inflate(R.layout.layout_toast, null)
            val tvToast = view.findViewById<TextView>(R.id.tv_toast)
            tvToast.text = message
            it.view = view
            it.show()
        }


    }

}